﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace SvgApplication.Authorization
{
    public class AuthenticationHelper
    {
        /// <summary>
        /// performs a login for the specified user data 
        /// adds a cookie to the response, that contains the data provided 
        /// </summary>
        /// <param name="httpContextBase">the HttpContextBase used to add the cookie in the request</param>
        /// <param name="ud">the data to pass in the cookie</param>
        /// <param name="timeoutInMinutes">the cookie timeout</param>
        public void DoLogin(HttpContextBase httpContextBase, UserData ud, int timeoutInMinutes)
        {
            try
            {
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, ud.UserName, DateTime.Now, DateTime.Now.AddMinutes(timeoutInMinutes), false, ud.ToXml());
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                httpContextBase.Response.Cookies.Add(authCookie);
            }
            catch { }
        }

        /// <summary>
        /// expires a cookie
        /// </summary>
        /// <param name="httpContextBase">the HttpContextBase used to add the cookie in the request</param>
        /// <param name="cookieName">the cookie name</param>
        public void ExpireCookie(HttpContextBase httpContextBase, string cookieName)
        {
            if (httpContextBase.Request.Cookies[cookieName] != null)
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Expires = DateTime.Now.AddDays(-1d);
                httpContextBase.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// logs off the user
        /// </summary>
        /// <param name="httpContextBase">the HttpContextBase used to add the cookie in the request</param>
        /// <param name="token">additional token used by the user, which is expired</param>
        public void DoLogOff(HttpContextBase httpContextBase, string token = "")
        {
            this.ExpireCookie(httpContextBase, ".ASPXAUTH");
            this.ExpireCookie(httpContextBase, "AccessibleMenus");

            //expire the token
            if (!string.IsNullOrEmpty(token))
            {
                //TokenManager.GetTokenManager().ExpireToken(token);
            }
            //Session.Clear();
            //Session.Abandon();
        }
    }
}
